package com.shelpe.services.auth.configuration;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;

import com.shelpe.services.auth.entity.Users;
import com.shelpe.services.auth.repository.AuthRepository;
import com.shelpe.services.auth.repository.UsersRepository;
import com.shelpe.services.auth.service.SandboxTokenService;
import com.shelpe.services.auth.service.TokenService;
import com.shelpe.services.auth.service.TokenServiceImpl;

@Configuration
public class TokenConfiguration {

	@Bean
	@Profile({"dev", "local"})
	public TokenService sandboxTokenService(@Qualifier("sandboxDataSource") DataSource ds,AuthRepository authRepository, final UsersRepository usersRepository){
		final SandboxTokenService sandbox = new SandboxTokenService();
		JdbcTemplate template = new JdbcTemplate(ds);
		sandbox.setTemplate(template);
		
		final TokenServiceImpl proxy = new TokenServiceImpl();
		proxy.setAuthRepository(authRepository);
		proxy.setUsersRepository(usersRepository);
		
		return new TokenService(){

			@Override
			public TokenService.UserInfo getToken(String nick) {
				if(nick == null){
					return null;
				}
				
				return nick.indexOf("sandbox_") > -1?sandbox.getToken(nick):proxy.getToken(nick);
			}

			@Override
			public TokenService.UserInfo getToken(long userId) {
				Users u = usersRepository.findTopByUserId(userId);
				if(u == null){
					return sandbox.getToken(userId);
				}
				String nick = u.getNick();
				return this.getToken(nick);
			}
			
		};
	}
	
	@Bean
	@Profile("product")
	public TokenService tokenService(AuthRepository authRepository, UsersRepository usersRepository){
		TokenServiceImpl service = new TokenServiceImpl();
		service.setAuthRepository(authRepository);
		service.setUsersRepository(usersRepository);
		return service;
	}
}
